const Sequelize = require('sequelize')
const Op = Sequelize.Op
const sequelize = require('../db/dbconfig')
const PostModel = require('../db/models/posts')
const {update_project_info_schema} = require("../schema/projectInfo");
const url = require("url");
const fs = require("querystring");
const postModel = PostModel(sequelize)

// 增
exports.addPost = async (req, res) => {
  try {
    const postinfo = req.body
    const user = req.auth
    let results = await postModel.create({
      user_id: user.user_id,
      post_title: postinfo.post_title,
      post_biography: postinfo.post_biography,
      post_pic: postinfo.post_pic,
      post_content: postinfo.post_content
    })
    res.myMsg('文章发布成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}
// 删
exports.delPost = async (req, res) => {
  try{
    let results = await postModel.update({
      is_delete: 1
    },{
      where: {
        post_id: req.params.id
      }
    })
    if(results[0] === 0) return res.myMsg('删除失败，文章不存在')
    res.myMsg('文章删除成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}
// 改
exports.updatePost = async (req, res) => {
  try {
    const postinfo = req.body
    let is_exist = await postModel.findOne({
      where: {
        is_delete: 0,
        post_id: postinfo.post_id
      }
    })
    if(is_exist === null) return res.myMsg('修改失败，文章不存在')
    let results = await postModel.update({
      post_title: postinfo.post_title===''? is_exist.post_title:postinfo.post_title,
      post_biography: postinfo.post_biography===''? is_exist.post_biography : postinfo.post_biography,
      post_pic: postinfo.post_pic===''? is_exist.post_pic:postinfo.post_pic,
      post_content: postinfo.post_content===''? is_exist.post_pic:postinfo.post_pic
    },{
      where: {
        post_id: postinfo.post_id
      }
    })
    if(results === '') return res.myMsg('修改失败')
    res.myMsg('修改成功',0)
  }catch (e) {
    res.myMsg(e)
  }
}
// 查
exports.getPostAll = async (req, res) => {
  try {
    const {query} = url.parse(req.url, false);
    let temp = parseInt(fs.parse(query).offset[0])
    const offset = temp%2===0? temp:temp-1
    let results = await postModel.findAndCountAll({
      where: {
        is_delete: 0
      },
      order: [
        ['post_id', 'asc']
      ],
      limit: 2,
      offset
    })
    res.myMsg(results,0)
  }catch (e) {
    res.myMsg(e)
  }
}